import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { UtilsService } from './utils.service';
@Injectable({
  providedIn: 'root'
})
export class CacheService {

  private userInfo: object = null;
  public isLogin = false;
  constructor(
    private utilsService: UtilsService,
    private nzmsg: NzMessageService,
    private router: Router
  ) { }

  async getUserInfo() {
    if (!this.userInfo) {
      try {
        let ufString = await window.sessionStorage.getItem('uf');
        if (!ufString) {
          this.clearUserInfo();
          this.router.navigateByUrl('/login');
          return this.userInfo;
        }
        ufString = this.utilsService.uncompileStr(ufString);
        const uf = JSON.parse(ufString);
        if (uf.t_exp < new Date().valueOf()) {
          this.nzmsg.error('用户信息已过期,请重新登陆!');
          this.clearUserInfo();
          this.router.navigateByUrl('/login');
          return this.userInfo;
        }
        this.isLogin = true;
        this.userInfo = uf;
      } catch (error) {
        this.nzmsg.error('读取用户信息出错,请重新登陆!');
        this.clearUserInfo();
        this.router.navigateByUrl('/login');
        console.error(error);
        return this.userInfo;
      }
    }
    return this.userInfo;
  }

  getToken() {
    if (this.userInfo && this.userInfo['token']) {
      return this.userInfo['token'];
    }
    return '';
  }

  updateUserInfo(data: object) {
    this.isLogin = true;
    this.userInfo = data;
  }

  clearUserInfo() {
    this.userInfo = null;
    this.isLogin = false;
    window.sessionStorage.removeItem('uf');
  }
}
